Triangle
LeetCode 120 | Difficulty: Mediumβ
MediumProblem Descriptionβ
Given a triangle array, return the minimum path sum from top to bottom.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
Example 1:
Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output: 11
Explanation: The triangle looks like:
2
3 4
6 5 7
4 1 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
Example 2:
Input: triangle = [[-10]]
Output: -10
Constraints:
- `1 <= triangle.length <= 200`
- `triangle[0].length == 1`
- `triangle[i].length == triangle[i - 1].length + 1`
- `-10^4 <= triangle[i][j] <= 10^4`
Follow up: Could you do this using only O(n) extra space, where n is the total number of rows in the triangle?
Topics: Array, Dynamic Programming
Approachβ
Dynamic Programmingβ
Break the problem into overlapping subproblems. Define a state (what information do you need?), a recurrence (how does state[i] depend on smaller states?), and a base case. Consider both top-down (memoization) and bottom-up (tabulation) approaches.
Optimal substructure + overlapping subproblems (counting ways, min/max cost, feasibility).
Solutionsβ
Solution 1: C# (Best: 149 ms)β
| Metric | Value |
|---|---|
| Runtime | 149 ms |
| Memory | N/A |
| Date | 2017-11-17 |
public class Solution {
public int MinimumTotal(IList<IList<int>> triangle) {
var len = triangle.Count;
var minlen = new int[triangle.Count+1];
for (int i = len-1; i >=0 ; i--)
{
for (int j = 0; j <= i; j++)
{
minlen[j] = Math.Min(minlen[j], minlen[j+1])+triangle[i][j];
}
}
return minlen[0];
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Dynamic Programming | $O(n)$ | $O(n)$ |
Interview Tipsβ
- Discuss the brute force approach first, then optimize. Explain your thought process.
- Define the DP state clearly. Ask: "What is the minimum information I need to make a decision at each step?"
- Consider if you can reduce space by only keeping the last row/few values.